<?php
// +----------------------------------------------------------------------
// | 后台用户管理
// +----------------------------------------------------------------------
namespace app\common\model;
use think\Model;
use think\Validate;

class Coupon extends Model
{
	use \base\model\ModelTrait;
	//表名
    protected $name = 'coupon';  
	//主键	
	protected $pk = 'id';  	
	//自动完成
	protected $auto = [];
	// 自动完成, 只在新增的时候有效
	protected $insert = [];
	// 自动完成, 只在更新的时候有效
	protected $update = [];
	//只读字段
	protected $readonly = [];
	//模型关联，一对多关联
	public function comments(){
        return $this->hasMany('coupon_user','coupon_id','id');
    }
	/**
    * 错误信息
    */
	public $errorInfo;
	/**
    * 验证规则
    */
	protected $rule = [
		'shop_id'=>'require|integer',
		//'goods_id'=>'require',
		'name'=>'require',
    	'price' => 'require|float|min:0',
    	'start_time' => 'require|date',
    	'stop_time' => 'require|date|gt:start_time',
	];
	
	/**
     * 删除
     * @param type $user_id
     * @param type $new_pwd
     * @return type
     */
	public function setDel($ids,$v)
    {
    	return $this->where('id','in', $ids)->update(['is_del' => $v]);
    }
	
	/**
     * 设置启用
     * @param type $ids
     * @param type $v
     * @return type
     */
	public function setEnable($ids,$v)
    {
    	return $this->where('id','in', $ids)->update(['is_enable' => $v]);
    }
	
	/**
	* 优惠券数量设置
	 * @param type $id
     * @param type $add_num
     * @return type $reduce_num
	*/
	public function setTotalNum($id,$add_num=0,$reduce_num=0){
		$model = new self;
		if($reduce_num > $add_num){ //减
			$num = $reduce_num - $add_num;
			$result = $model::where('id',$id)->setDec('total_num', $num);
			$result = $result &&  $model::where('id',$id)->setDec('remain_num', $num);
		}else if($reduce_num != $add_num){ // 加
			$num = $add_num - $reduce_num;
			$result = $model::where('id',$id)->setInc('total_num',$num);
			$result = $result && $model::where('id',$id)->setInc('remain_num',$num);
		}
		if ($result !== false && $result !== 0) {
	        return true;
	    } else {
	    	$this->errorInfo =  "异常错误, 注意结果不能为负数！";
	    	return false;
	    }
	}
	
	/**
	* 优惠券恢复数量
	 * @param type $id
     * @param type $num
	*/
	public function replyNum($id,$num=0){
		$model = new self;
		$result =  $model::where('id',$id)->setInc('remain_num', $num);
		if ($result !== false && $result !== 0) {
	        return true;
	    } else {
	    	$this->errorInfo = "异常错误, 注意结果不能为负数！";
	    	return false;
	    }
	}
	
	/**
    * 获取优惠券列表
    * @param type $id
    * @return type
    */
	public function getCouponList($where=[],$pageIndex=0,$pageSize=20)
    {
		$model = new self;
		$model = $model->withCount(['comments'=>'receive_num']);
		$model = $model->where($where);
		$model = $model->where('is_del',0);
		$model = $model->order("add_time","desc");
		if($pageIndex>0){
			$model = $model->page($pageIndex,$pageSize);
		}
		return $model->select();
    }
    
    /**
     * 获取已发布并可用状态的优惠券
     * @param type $user_id
     * @param type $new_pwd
     * @return type
     */
	public function getCoupon($ids=0,$startTime='',$isGetStart=false)
    {
    	$uid = request()->userId ?: request()->uid;
    	$model = new self;
		$model = $model->where(function ($query) use ($startTime,$isGetStart){
			$query = $query->where('is_del',0);
			$query = $query->where('status',1);
			!$isGetStart && $query = $query->where('start_time','<', date("Y-m-d H:i:s"));
			$query = $query->where('stop_time','>', date("Y-m-d H:i:s"));
			$startTime && $query = $query->where('stop_time','>=', $startTime);
		})->whereor(function($query) use ($ids){
			$query->where('id','in',$ids);
		});
		$model = $model->field('is_del,add_time,status,cid,warning_value,is_permanent,code',true);
		$model = $model->field('id as value,name as label');
		$model = $model->order('add_time', 'desc');
		
		return $model->select();
    }
    
    /**
    * 获取用户可领优惠券列表
    * @param type $id
    * @return type
    */
	public function userCanReceive($uid,$goods_id=0)
    {
		$subQuery = model('coupon_user')
			    ->field('coupon_id,count(id) as receive_num')
				->group("coupon_id")
				->where("uid",$uid)
			    ->buildSql();
				
    	$d = date("Y-m-d");
		$model = new self;
		$model = $model->alias('a');
		$model = $model->leftJoin("$subQuery b",'a.id = b.coupon_id');
		$model = $model->leftJoin("goods c","c.id = $goods_id");
		$model = $model->field('a.*');
		$model = $model->field('ifnull(b.receive_num,0) as receive_num');
		$model = $model->order("a.add_time","desc");
		$model = $model->where('a.is_del',0);
		$model = $model->where('start_time','<=',$d);
		$model = $model->where('stop_time','>=',$d);
		$model = $model->where(function ($query) use($goods_id) {
			$query->whereNull('a.shop_id');
			$query->whereOr('a.shop_id','0');
			$query->whereOr('a.shop_id','');
			$query->whereOr([['','exp',\Db::raw("find_in_set(a.shop_id,c.shop_id)")]]);
		});
		$model = $model->where(function ($query) use($goods_id) {
			$query->whereNull('a.goods_id');
			$query->whereOr('a.goods_id','');
			$query->whereOr([['','exp',\Db::raw("find_in_set($goods_id,a.goods_id)")]]);
		});
		
		return $model->select();
    }
	
	/**
	* 优惠券发放
	* @param  $cids  			必填 		优惠券id,多个逗号分割 
	* @param  $uids   		选填 		用户id，多个逗号分割 ,按指定用户发放
	*/
	public function grant($cids,$uids="",$is_give=0,$num=1,$get_mode='receive'){
		//获取模型
		$coupon =  new self;

		//查询用户数量
		$userIds = model('user')->where('id','in',$uids)->column('id');
		//判断用户数量
		if( count($userIds) == 0){
			$this->errorInfo = "当前条件所发放的用户数量为0，发放失败！";
			return false;
		}
		//查询优惠券 
		$subQuery = model('coupon_user')
		    ->field('parent_id,count(id) as receive_num')
			->group("parent_id")
			->where("uid",'in',$userIds)
		    ->buildSql();
		$coup =  $coupon->alias('a')
			->leftJoin("$subQuery b",'a.id = b.parent_id')
			->lock(true)
			->field('a.*')
			->field('ifnull(b.receive_num,0) as receive_num')
			->where('a.id','in',$cids)
			->select();
		
		//判断优惠券是否存在
		if( count($coup) < 1 ){
			$this->errorInfo = "优惠券不存在！";
			return false;
		}
		
		// 判断优惠券数量
		foreach ($coup as $key => $itme) {
			if( (count($userIds)  + ($num-1)) > $itme['remain_num'] ){
				$this->errorInfo ='【'.$itme['name']."】剩余数量不足发放！";
				return false;
			}
			if( $itme['stop_time'] <= date('Y-m-d') ){
				$this->errorInfo = '【'.$itme['name']."】已过期，不能发放！";
				return false;
			}
			if( $itme['can_num'] > 0 && $itme['can_num'] <=  $itme['receive_num']  ){
				$this->errorInfo = '【'.$itme['name']."】已达到可领取数，不能再次领取！";
				return false;
			}
		}
			
		//更新优惠券数量
		if( $coupon->where("id",'in',$cids)->setDec('remain_num', (count($userIds) + ($num-1)) ) == 0){
			$this->errorInfo = "发送错误 , 更新优惠券数量失败！";
			return false;
		}
		
		//发放
		$list = [];
		foreach ( $coup as $k => $itme ) {
			$stop_time = ($itme['can_day'] ?: 1000) - 1;
			foreach ( $userIds as $key => $id ) {
				$list[] = [
					'uid' => $id,
					'shop_id' => $itme['shop_id'],
					'goods_id' => $itme['goods_id'],
					'parent_id' => $itme['id'],
					'price' =>  $itme['price'],
					'img' =>  $itme['img'],
					'name' => $itme['name'],
					'type' => $itme['type'],
					'start_time' => date('Y-m-d'),
					'stop_time' => date("Y-m-d",strtotime("+$stop_time  day")),
					'can_proj_type' => $itme['can_proj_type'],
					'can_day' => $itme['can_day'],
					'get_mode' => $get_mode,
					'remark' => $itme['remark'],
					'remind_mode' => $itme['remind_mode'],
					'is_remind' => $itme['is_remind'],
					'is_discount' => $itme['is_discount'],
					'is_give' => $is_give,
					'full_cond_reduce' => $itme['full_cond_reduce'],
					'fracture' => $itme['fracture'],
					'num'=> $num ?? 1
				];
			};
		}
		
		//发放
		if( !model('CouponUser')->saveAll($list) ){
			$this->errorInfo = "发送失败！";
			return false;
		}
		
		return  true;		
	}
	
}







